const express = require('express');
const path = require('path');

var app = new express();


let products =[{
    "id":1,"name":"玩具","brand":"乐高","price":150
}];


app.get('/productPage',function (req,res) {
    let  currentPage =parseInt(req.query['currentPage']);
    let  perPage = parseInt(req.query['perPage']);
    let start = (currentPage-1)*perPage;
    let end = start+perPage;
    var item = products.slice(start,end);

    res.json({item,sum:products.length})
})

//主页
app.get('/product.html',function (req,res) {
    let index = './app/product.html';
    index = path.resolve(index);
    res.sendFile(index);
})
//新增商品页面
app.get('/add.html',function (req,res) {
    let index = 'app/add.html';
    index = path.resolve(index);
    res.sendFile(index);
})

//新增商品处理
app.get('/add',function (req,res) {
    let  product =req.query['product'];
    products.push(product);
    res.json({status: 'ok', code: '200'});
})

app.get('/del',function (req,res) {
    let  id =req.query.id;
    let index = products.findIndex(item => {
        return item.id == id;
    });
    products.splice(index, 1);

    res.json({status: 'ok', code: '200'});
})

app.get('/modify.html',function (req,res) {
    let index = './app/modify.html'
    index = path.resolve(index);
    res.sendFile(index);
});

app.get('/modify',function (req,res) {
    let product =req.query['product'];
    let id = product.id;
    let item=products.find(value => {
        return value.id ==id;
    })

    item.name= product.name;
    item.brand= product.brand;
    item.price= product.price;

    res.json({status: 'ok', code: '200'});
});
//根据id获取数据
app.get('/getProduct',function (req,res) {
    let  id =req.query['id'];
    let item = products.find(item => {
        return item.id == id;
    });

    res.json({status: 'ok', code: '200', item});
})


app.use('/ststic', express.static(__dirname + '/app/ststic'))

var  server = app.listen(8080,function () {

    var hoost = server.address().address;

    var port = server.address().port;

    console.log("应用实例，访问地址为http://%s:%s,host,port")

});